package com.tangsm.spring.boot.async.service.impl;

import com.tangsm.spring.boot.async.service.AsyncMultitaskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;

/**
 * 多任务异步调用业务接口实现
 *
 * @author tangsm
 */
@Service
public class AsyncMultitaskServiceImpl implements AsyncMultitaskService {
    private static final Logger log = LoggerFactory.getLogger(AsyncMultitaskServiceImpl.class);

    /**
     * 无返回值异步方法
     */
    @Async("customTaskExecutor")
    @Override
    public void async(int i) {
        try {
            log.info("多任务异步调用无返回值，请求号：{}，等待两秒", i);
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("多任务异步调用无返回值，请求号：{}", i);
    }

    /**
     * 有返回值异步方法
     */
    @Async("customTaskExecutor")
    @Override
    public Future<String> asyncFuture(int i) {
        try {
            log.info("多任务异步调用有返回值，请求号：{}，等待两秒", i);
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        log.info("多任务异步调用有返回值，请求号：{}", i);
        Future<String> future = new AsyncResult<>("ok:" + i);
        return future;
    }
}
